package com.itheima.reggie.controller;

import com.itheima.reggie.common.VerificationCodeUtils;
import com.itheima.reggie.entity.Information;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码短信
     *
     * @param phoneNumber
     * @param request
     * @return
     */
    @PostMapping("/getVerificationCode")
    public R sendVerificationCode(@RequestBody String phoneNumber, HttpServletRequest request) {

        System.err.println("phoneNumber:" + phoneNumber);

        if (phoneNumber != null && phoneNumber.length() != 0) {

            //生成随机的4位验证码
            String verificationCode = VerificationCodeUtils.generateValidateCode(4).toString();
            System.err.println("verificationCode:" + verificationCode);

            //调用阿里云提供的短信服务API完成发送短信
//            String sendResult = SmsUtils.sendSms(phoneNumber, verificationCode);
//            System.err.println("sendResult:" + sendResult);//200


            //需要将生成的验证码保存到Session
//            request.getSession().setAttribute(phoneNumber, verificationCode);

            //需要将生成的验证码保存到Redis,设置过期时间
            redisTemplate.opsForValue().set(phoneNumber, verificationCode, 5, TimeUnit.MINUTES);

            return R.success("验证码已发送,请输入验证码");

        }

        return R.error("短信发送失败");
    }


    @PostMapping("/login")
    public R login(@RequestBody Information information, HttpSession session) {

        System.err.println("information:" + information);
        System.err.println(information.getPhone() + ":" + information.getCode());

         //从Session中获取发送验证码时存储的验证码
//        String verificationCode = (String) session.getAttribute(information.getPhone());

        //从Redis中获取缓存的验证码
        String verificationCode = (String)redisTemplate.opsForValue().get(information.getPhone());


        if (verificationCode != null && verificationCode.equals(information.getCode())) {
            //登陆成功
            //根据电话查询user表,判断是否是新用户,如果是新用户直接注册(加入user表)
            User user = userService.selectByPhone(information.getPhone());

            Long oldUserId = null, newUserId = null;

            if (user != null) {
                oldUserId = user.getId();
                session.setAttribute("user", oldUserId);//将登录的用户键值对到session中,供后续页面使用
            } else {
                //是新用户
                user = new User();
                user.setPhone(information.getPhone());
                user.setStatus(1);
                user.setName("新用户" + user.getPhone());
                newUserId = userService.insert(user);//id是user表的主键,有auto_increment,当user==null时,id属性自然为null,往user插入后,变成自增量,通过注解将数据库表中自增字段id自动生成的值从mapper->service->controller
                session.setAttribute("user", newUserId);//将登录的用户键值对到session中,供后续页面使用
            }

            System.err.println("oldUserId:" + oldUserId);
            System.err.println("newUserId:" + newUserId);

            //登陆成功后,从Redis中删除缓存的验证码
            redisTemplate.delete(information.getPhone());

            return R.success(user);
        }
        return R.error("验证码错误登录失败");
    }
}
